/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rhdtp.demopf.services;

import com.rhdtp.demopf.model.dao.PeliculaDAO;
import com.rhdtp.demopf.model.dto.Pelicula;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * @author rhdtp
 */
public class ImagesDeployService implements ServletContextListener {

    ServletContext context;
    private static Logger logger = Logger.getLogger(ImagesDeployService.class);
    private PeliculaDAO peliculaDAO;

    @Override
    public void contextInitialized(ServletContextEvent contextEvent) {
        List<Pelicula> peliculas;
        String imagesPath;
        ApplicationContext springContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        peliculaDAO = (PeliculaDAO) springContext.getBean("peliculaDAO");
        peliculas = peliculaDAO.list();
        context = contextEvent.getServletContext();
        imagesPath = "/resources/images/peliculas/";
        File imagenArte;
        FileOutputStream fileOutput;
        String relativeWebPath;
        String absoluteDiskPath;

        if (!peliculas.isEmpty()) {
            for (Pelicula p : peliculas) {
                try {
                    relativeWebPath = imagesPath + p.getId() + "." + p.getTipoPortada();
                    absoluteDiskPath = context.getRealPath(relativeWebPath);
                    imagenArte = new File(absoluteDiskPath);
                    fileOutput = new FileOutputStream(imagenArte);
                    fileOutput.write(p.getPortada());
                    fileOutput.close();
                } catch (IOException ioex) {
                    logger.error(ioex.getCause(), ioex);
                }
            }
        } else {
            logger.info("No se creo ninguna portada ya que la lista se encuentra vacia.");
        }

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        logger.info("Se desintala la aplicacion");
    }

    public PeliculaDAO getPeliculaDAO() {
        return peliculaDAO;
    }

    public void setPeliculaDAO(PeliculaDAO peliculaDAO) {
        this.peliculaDAO = peliculaDAO;
    }

}
